<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//define("APPID", "wx5672506691fea394"); //appid值
//define("APPSECRET", "a10b06bf4f7519152bad03311f212e65"); //密钥

class MediaController extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url_helper');
		$this->load->library('session');
		$this->load->library('AccessTokenClass');
		$this->load->library('Vars');
	}
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 *        http://example.com/index.php/welcome
	 *    - or -
	 *        http://example.com/index.php/welcome/index
	 *    - or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */



	public function save_media(){
		$media_id=$this->input->post('media_id');
		$access_token=$this->accesstokenclass->get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/media/get?access_token='.
			$access_token.'&media_id='.$media_id;
//		$res = file_get_contents($url); //获取文件内容或获取网络请求的内容
////echo $res;
//		$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
		$filecontent=$this->download_weixin_file($url);
		$path='/resources/image/upload';
		$filename=$this->save_weixin_file($path,$filecontent);
		$img_url= base_url().'resources/image/upload/'.$filename;
		header('content-type:application:json;charset=utf8');
		header('Access-Control-Allow-Origin:*');
		header('Access-Control-Allow-Methods:POST');
		header('Access-Control-Allow-Headers:x-requested-with,content-type');
		$result = array();
		$result['isSuccess'] = true;
		$result['errorMessage'] = '';
		$result['data'] = $img_url;
		echo json_encode($result, JSON_UNESCAPED_UNICODE);

	}

	public function download_weixin_file($url){
		$ch=curl_init($url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch,CURLOPT_NOBODY,0);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$package=curl_exec($ch);
		$httpinfo=curl_getinfo($ch);
		curl_close($ch);
		$image_all=array_merge(array('header'=>$httpinfo),array('body'=>$package));
		return $image_all;
	}

	public function save_weixin_file($path,$filecontent){
		$filetype='.jpg';
		$filename=time().$filetype;
		$filename1=$_SERVER['DOCUMENT_ROOT'].$path.'/'.$filename;
		$local_file=fopen($filename1,'w');
		if(false!=$local_file){
			if(false!=fwrite($local_file,$filecontent['body'])){
				fclose($local_file);
			}
		}
		return $filename;
	}
}


